package handler

import (
	"github.com/gin-gonic/gin"
	"lib/http"
	"lib/structs/enum"
	"lib/structs/lms"
	"lms/repository"
	"lms/service"
)

var StudyingApi = new(studyingApi)

type studyingApi struct {
}

func (a studyingApi) StudentGetPage(c *gin.Context) {
	var in lms.SearchCourse
	if err := c.ShouldBindQuery(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	self := http.GetCurrentUser(c)
	li, err := service.CourseService.GetCourse(in, self.UserID, self.OrgId)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.Ok(c, li)
}

func (a studyingApi) CourseDetail(c *gin.Context) {
	in := struct {
		CourseId int64 `uri:"courseId"`
	}{}
	if err := c.ShouldBindUri(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	// todo 课程详情在这里封装
	cour, err := repository.CourseDB.FindById(in.CourseId)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.Ok(c, cour)
}

func (a studyingApi) CoursewareDetails(c *gin.Context) {
	in := struct {
		CourseId int64 `uri:"courseId"`
	}{}
	if err := c.ShouldBindUri(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	li, err := repository.CoursewareDb.FindCoursewareListByCourseId(in.CourseId)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.Ok(c, li)
}

func (a studyingApi) GetCoursewareResource(c *gin.Context) {
	in := struct {
		CoursewareId int64 `uri:"coursewareId"`
		CourseId     int64 `uri:"courseId"`
	}{}
	if err := c.ShouldBindUri(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	self := http.GetCurrentUser(c)
	// 检查课程权限
	b, err := service.CourseService.CheckCourseJurisdiction(in.CourseId, self.UserID, self.OrgId)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	if !b {
		http.BadWithCode(c, enum.ErrorMap.CourseAccessDenied)
		return
	}
	// 检查课件权限
	cw, err := repository.CoursewareDb.FindById(in.CoursewareId)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	if !cw.IsPublic {
		cou, err := repository.CourseDB.FindById(in.CourseId)
		if err != nil {
			http.BadWithDB(c, err)
			return
		}
		if cou.CreatorId != cw.CreatorId {
			http.BadWithCode(c, enum.ErrorMap.CoursewareAccessDenied)
			return
		}
	}
	dto := lms.CoursewareDto{
		Courseware:  cw,
		ResourceUri: service.CourseService.GetUri(cw),
	}
	// todo coursewareDto 封装
	http.Ok(c, dto)
}
